app.factory('MyFactory', function ($http, $window, $interval) {

    var factory = {
        //post请求
        PostAjax: function (url, data, successFn, failFn) {
            $http({
                method: 'POST',
                url: url,
                data: data,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function (obj) {
                    var str = [];
                    for (var s in obj) {
                        str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                    }
                    return str.join("&");
                }
            }).then(function successCallback(req) {
                if (typeof req.data == 'string') {
                    if (req.data.indexOf('!DOCTYPE') > -1) {
                        localStorage.removeItem('userid');
                        localStorage.removeItem('isSelect');
                        location.href = '/login.html'
                    }
                }
                successFn(req.data)
            }).catch(function (req) {
                failFn(req)
            })
        },
        //post同步请求
        PostAjaxs: function (url, data, successFn, failFn) {
            $http({
                method: 'POST',
                url: url,
                data: data,
                async: false,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function (obj) {
                    var str = [];
                    for (var s in obj) {
                        str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                    }
                    return str.join("&");
                }
            }).then(function successCallback(req) {
                if (typeof req.data == 'string') {
                    if (req.data.indexOf('!DOCTYPE') > -1) {
                        localStorage.removeItem('userid');
                        localStorage.removeItem('isSelect');
                        location.href = '/login.html'
                    }
                }
                successFn(req.data)
            }).catch(function (req) {
                failFn(req)
            })
        },
        //get请求
        GetAjax: function (myurl, mydata, successFn, failFn) {
            $http({
                method: 'GET',
                url: myurl,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                transformRequest: function (obj) {
                    var str = [];
                    for (var s in obj) {
                        str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                    }
                    return str.join("&");
                }
            }).then(function (data) {
                successFn(data)
            })
                .catch(function () {
                    failFn()
                })
        },

        //get请求
        GetAjaxs: function (myurl, mydata, successFn, failFn) {
            $http({
                method: 'GET',
                url: myurl,
                params: {
                    'html': mydata
                },
                transformRequest: function (obj) {
                    var str = [];
                    for (var s in obj) {
                        str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                    }
                    return str.join("&");
                }
            }).then(function (data) {
                successFn(data)
            })
                .catch(function (s) {
                    failFn()
                })
        },
        //选择分页长度


        //分页数组  需要传入的数据（$scope,页码，总页数，请求地址，搜索的内容（json格式，没有则传空json），回调函数，失败回调函数）
        PageArr: function (obj, selPage, totalCount, url, searchData, callback, failback) {
            var that = this;
            var totalCount = totalCount > 5 ? 5 : totalCount;
            obj.pageArr = []
            for (var i = 0; i < totalCount; i++) {
                obj.pageArr.push(i + 1);
            }
            obj.selPage = selPage;
            obj.selectPage = function (page) {
                if (page < 1 || page > obj.totalCount) {
                    if (page < 1) {
                        page = 1
                    };
                    if (page > obj.totalCount) {
                        page = obj.totalCount
                    };
                };
                if (page == 1) {
                    var newPageArr = [];
                    for (var i = 0; i < (5 > obj.totalCount ? obj.totalCount : 5); i++) {
                        newPageArr.push(i + 1);
                    }
                    obj.pageArr = newPageArr;
                    obj.loaded = true;
                }
                if (page == 2) {
                    var newPageArr = [];
                    for (var i = 0; i < (5 > obj.totalCount ? obj.totalCount : 5); i++) {
                        newPageArr.push(i + 1);
                    }
                    obj.pageArr = newPageArr;
                    obj.loaded = true;
                }
                if (page > 2 || page <= page - 2) {
                    var newPageArr = [];
                    for (var i = (page - 3); i < ((page + 2) > obj.totalCount ? obj.totalCount : page + 2); i++) {
                        newPageArr.push(i + 1)
                    }
                    newPageArr.length > 5 ? newPageArr.length = 5 : newPageArr.length = newPageArr.length;
                    obj.pageArr = newPageArr;
                    obj.loaded = true;
                }
                //if(page>){obj.pageArr=[obj.totalCount-4,obj.totalCount-3,obj.totalCount-2,obj.totalCount-1,obj.totalCount]}

                obj.selPage = page;

                obj.isActivePage(page)
                searchData.pageNo = page;
                //请求更新页面数据
                that.PostAjax(url, searchData, function (req) {
                    var pageData = req;
                    obj.loaded = false;
                    callback(pageData)
                }, function () {
                    failback();
                })
            }
            obj.isActivePage = function (page) {
                return obj.selPage == page
            };
            obj.nextPage = function () {
                obj.selectPage(obj.selPage + 1)
            };
            obj.prevPage = function () {
                obj.selectPage(obj.selPage - 1)
            };
            obj.fanelPage = function () {
                obj.selectPage(obj.totalCount);
            };
            obj.firstPage = function () {
                obj.selectPage(1);
            };
        },

        /***
         **obj  $scope
         ** //页面行数选择
         **
         */
        selectPage: function (obj) {

            obj.searchData.pageNo = '1';
            obj.goPage = function (e) {
                //enter键盘事件
                if (e) {
                    var keycode = window.event ? e.keyCode : e.which; //获取按键编码  
                    if (keycode == 13) {
                        obj.selectPage(obj.searchData.pageNo);
                    }

                } else {

                    obj.selectPage(obj.searchData.pageNo);

                }

            }

            obj.searchData.pageSize = '5';
            obj.selectPageSize = function () {
                obj.searchData.pageNo = 1;
                obj.upData();
            }

            //搜索    
            obj.search = function (e) {
                if (e) {
                    var keycode = window.event ? e.keyCode : e.which;
                    if (keycode == 13) {
                        obj.searchData.pageNo = 1;
                        obj.upData();
                    }
                } else {
                    obj.searchData.pageNo = 1;
                    obj.upData();
                }
            }
        },


        /***
         **obj  $scope
         **id String  带#
         **startTime String 对应要传给后台的开始时间key
         **endTime
         **
         */
        //选项卡1
        Date: function (obj, id, startTime, endTime) {
            var nowDate = new Date();
            var timeStr = nowDate.toISOString().substr(0, 10);
            App.d(id).value = timeStr + ' - ' + timeStr;
            //时间调用
            obj.searchData[startTime] = timeStr;
            obj.searchData[endTime] = timeStr;

            //更新用户搜索时间
            $(id).daterangepicker({
                minDate: '2017-1-1'
            }, function (start, end, label) {
                // obj.$apply(obj.searchData[startTime] = strData.substring(0, 10));
                // obj.$apply(obj.searchData[endTime] = strData.substring(12));

            });
            obj.clearTime = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        //选项卡2 
        Date1: function (obj, id, startTime, endTime) {
            //更新用户搜索时间
            $(id).daterangepicker({
                minDate: '2017-1-1'
            }, function (start, end, label) {
                obj.$apply(obj.searchData1[startTime] = strData.substring(0, 10));
                obj.$apply(obj.searchData1[endTime] = strData.substring(12));
            });
            obj.clearTime1 = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        //选项卡3
        Date2: function (obj, id, startTime, endTime) {
            //更新用户搜索时间
            $(id).daterangepicker({
                minDate: '2017-1-1'
            });
            obj.clearTime = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        //选项卡4 
        Date3: function (obj, id, startTime, endTime, starts, ends) {
            //时间调用
            App.d(id).value = starts + ' - ' + ends;
            obj.searchData[startTime] = starts;
            obj.searchData[endTime] = ends;
            //更新用户搜索时间
            $(id).daterangepicker({
                timePicker: true, //显示时间
                timePicker12Hour: false, //时间制
                timePickerSeconds: true, //时间显示到秒
                // startDate: starts.moment().format('YYYY-MM-DD HH:mm'), //设置开始日期
                // endDate: ends.moment().format('YYYY-MM-DD HH:mm'), //设置结束器日期
                maxDate: ends, //设置最大日期
                minDate: starts, //设置最小日期
                timePickerIncrement: 60,
                format: "YYYY-MM-DD HH",
                // "opens": "center",
                // showWeekNumbers: true,
                locale: {
                    format: "YYYY-MM-DD HH", //设置显示格式
                    applyLabel: '确定', //确定按钮文本
                    cancelLabel: '取消', //取消按钮文本
                    customRangeLabel: '自定义',
                    fromLabel: '',
                    toLabel: '',
                    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                        '七月', '八月', '九月', '十月', '十一月', '十二月'
                    ],
                    firstDay: 1

                },

            }, function (start, end, label) {
                obj.searchData[startTime] = start.format('YYYY-MM-DD HH');
                obj.searchData[endTime] = end.format('YYYY-MM-DD HH');
            });
            obj.clearTime = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        //选项卡5
        Date4: function (obj, id, startTime, endTime, start, end) {
            App.d(id).value = start + ' - ' + end;
            obj.searchData[startTime] = start;
            obj.searchData[endTime] = end;

            //更新用户搜索时间
            $(id).daterangepicker({
                minDate: '2017-1-1'
            }, function (start, end, label) {
                // obj.$apply(obj.searchData[startTime] = strData.substring(0, 10));
                // obj.$apply(obj.searchData[endTime] = strData.substring(12));

            });
            obj.clearTime = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        //选项卡6 
        Date5: function (obj, id, startTime, endTime, starts, ends) {
            //时间调用
            App.d(id).value = starts + ' - ' + ends;
            obj.searchData[startTime] = starts;
            obj.searchData[endTime] = ends;
            //更新用户搜索时间
            $(id).daterangepicker({
                timePicker: true, //显示时间
                timePicker12Hour: false, //时间制
                timePickerSeconds: true, //时间显示到秒
                // startDate: starts.moment().format('YYYY-MM-DD HH:mm'), //设置开始日期
                // endDate: ends.moment().format('YYYY-MM-DD HH:mm'), //设置结束器日期
                maxDate: ends, //设置最大日期
                minDate: starts, //设置最小日期
                timePickerIncrement: 1,
                format: "YYYY-MM-DD HH:mm",
                locale: {
                    format: "YYYY-MM-DD HH:mm", //设置显示格式
                    applyLabel: '确定', //确定按钮文本
                    cancelLabel: '取消', //取消按钮文本
                    customRangeLabel: '自定义',
                    fromLabel: '',
                    toLabel: '',
                    daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                        '七月', '八月', '九月', '十月', '十一月', '十二月'
                    ],
                    firstDay: 1

                },

            }, function (start, end, label) {
                obj.searchData[startTime] = start.format('YYYY-MM-DD HH:mm');
                obj.searchData[endTime] = end.format('YYYY-MM-DD HH:mm');
            });
            obj.clearTime = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        //选项卡7
        Date6: function (obj, id, startTime, endTime, starts, ends) {
            //时间调用
            App.d(id).value = starts + ' - ' + ends;
            obj.searchData[startTime] = starts;
            obj.searchData[endTime] = ends;
            //更新用户搜索时间
            $(id).daterangepicker({
                language: 'zh-CN',
                format: 'YYYY-MM',
                autoclose: true,
                minDate: '2017-01',
                maxDate: ends, //设置最大日期
                startView: 3,
                minView: 3,
                maxView: 4,
                forceParse: true,
                // locale: {
                //     monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                //         '七月', '八月', '九月', '十月', '十一月', '十二月'
                //     ],
                //     firstDay: 1

                // },
            }, function (start, end) {
                obj.searchData[startTime] = start.format('YYYY-MM');
                obj.searchData[endTime] = end.format('YYYY-MM');
            });
            obj.clearTime = function () {
                App.d(id).value = '';
                obj.searchData[startTime] = '';
                obj.searchData[endTime] = '';
            }

        },
        /***
         **
         **滚动
         **
         */
        unifySlide: function (obj, id, ele, up, down) {
            obj[up] = function () {
                var JGslide = document.querySelector(id);

                var JGP = JGslide.querySelectorAll(ele);

                var JGslideH = JGP[0].offsetHeight;
                JGslide.JGnum = 0;
                if (JGP.length <= 2) {
                    return
                }
                JGslide.JGnum == JGP.length - 2 ? JGslide.JGnum = 0 : JGslide.JGnum++;
                App.startMove(JGslide, {
                    'top': -JGslideH * JGslide.JGnum
                });
            };
            obj[down] = function () {
                var JGslide = document.querySelector(id);
                var JGP = JGslide.querySelectorAll(ele);
                var JGslideH = JGP[0].offsetHeight;
                JGslide.JGnum = 0;
                if (JGP.length <= 2) {
                    return
                }
                JGslide.JGnum == 0 ? JGslide.JGnum = JGP.length - 2 : JGslide.JGnum--;
                App.startMove(JGslide, {
                    'top': -JGslideH * JGslide.JGnum
                });
            };
        },
        /***
         **father 传入为字符串含.或#
         **child  拖动部分函数含.或#
         **拖拽函数
         **
         */
        hostDrag: function (father, child) {

            App.d(child).onmousedown = function (e) {
                var box = App.d(father)
                var slide = App.d(child);
                var Fh = box.offsetHeight;
                var Ch = slide.offsetHeight;


                var e = window.event || e || arguments.callee.caller.arguments[0];
                var Y = e.clientY;
                var T = slide.offsetTop;
                if (Ch > Fh) {
                    var h = Ch - Fh;
                    slide.onmousemove = function (e) {
                        var e = window.event || e || arguments.callee.caller.arguments[0];
                        var addT = e.clientY - Y;
                        var sT = addT + T
                        if (sT > 0) {
                            sT = 0
                        } else if (sT < Fh - Ch) {
                            sT = Fh - Ch
                        };
                        slide.style.top = sT + 'px';

                    }
                    document.onmouseup = function () {
                        slide.onmousemove = null;
                    }
                }
                return false
            }
        },

        /***
         **
         **统一监控折线图
         **
         */
        //两条线
        realTimeFn2: function (url, datax, id, title, lineName1, lineName2, Ytitle, color, color1, data1, data2, $scope) {

            var myChart = echarts.init(document.getElementById(id));
            var that = this;
            // 指定图表的配置项和数据
            option2 = {
                title: {
                    text: title,
                    textStyle: {
                        color: '#ccc',
                        fontSize: 14,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    data: [lineName1, lineName2],
                    top: 25,
                    left: 150,
                    textStyle: { //图例文字的样式
                        color: '#2ec7c9',
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    show: true,
                    x: '80%',
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    name: '时间',
                    axisLine: {
                        lineStyle: {
                            color: '#ccc'
                        },
                    },
                    axisLabel: {
                        interval: 11 //8
                        //              	    rotate:30
                    },
                    nameLocation: 'end',
                    nameGap: 0,
                    type: 'category',
                    boundaryGap: false,
                    data: datax
                },
                yAxis: {
                    axisLine: {
                        lineStyle: {
                            color: '#ccc'
                        },
                    },
                    splitLine: {
                        show: false
                    },
                    name: Ytitle,
                    type: 'value'
                },

                series: [{
                    name: lineName1,
                    color: '#fff',
                    type: 'line',
                    //                    areaStyle: {
                    //                        normal: {
                    //                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    //                                offset: 0,
                    //                                color: color[0]
                    //                            }, {
                    //                                offset: 1,
                    //                                color: color[1]
                    //                            }]),
                    //                        }
                    //                    },
                    //                    lineStyle:{
                    //                        normal:{
                    //                          width:0.5,
                    //                          color:'#00FF00'
                    //                        }
                    //                    },
                    itemStyle: {
                        normal: {
                            color: "#ff0000",
                            lineStyle: {
                                color: "#ff0000"
                            },

                        }
                    },
                    showSymbol: false,
                    hoverAnimation: false,
                    data: data1
                },
                {
                    name: lineName2,
                    type: 'line',
                    //                    areaStyle: {
                    //                        normal: {
                    //                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    //                                offset: 0,
                    //                                color: color1[0]
                    //                            }, {
                    //                                offset: 1,
                    //                                color: color1[1]
                    //                            }]),
                    //                        }
                    //                    },
                    //                    lineStyle:{
                    //                        normal:{
                    //                          width:0.5,
                    //                          color:'#fff'
                    //                        }
                    //                    },
                    itemStyle: {
                        normal: {
                            color: "#2ec7c9",
                            lineStyle: {
                                color: "#2ec7c9"
                            }
                        }
                    },
                    showSymbol: false,
                    hoverAnimation: false,
                    data: data2
                },
                    // {
                    //   name:'三级异常',
                    //   lineStyle:{
                    //         normal:{
                    //           width:0.5,
                    //           color:'#ff0000'
                    //         }
                    //     },
                    //   data:thirdData
                    // },
                    // {
                    //   name:'二级异常',
                    //   lineStyle:{
                    //         normal:{
                    //           width:0.5,
                    //           color:'#ff6000'
                    //         }
                    //     },
                    //   data:secondData
                    // },
                    // {
                    //   name:'一级告警',
                    //   lineStyle:{
                    //         normal:{
                    //           width:0.5,
                    //           color:'#ffc600'
                    //         }
                    //     },
                    //   data:fisrtData
                    // }
                ]
            };
            //获取当前时间n分钟后的时间函数
            function addMinutes(date, minutes) {
                minutes = parseInt(minutes);
                var interTimes = minutes * 60 * 1000;
                interTimes = parseInt(interTimes);
                var dateTime = new Date(Date.parse(date) + interTimes);
                var hour = dateTime.getHours();
                var min = dateTime.getMinutes();
                if (min < 10) {
                    min = '0' + min
                }
                return hour + ":" + min;
            }
            //时间格式转化为时间戳  
            function timeChangetype(stringTime) {
                var timestamp2 = Date.parse(new Date(stringTime));
                return timestamp2;
            }
            //  var timer = setInterval(function(){
            //  	       $scope.$apply(function(){
            //  	         //这里是想要定时刷新的逻辑
            //  	       });
            //  	     },3000);

            myChart.setOption(option2);
            $scope.timer = $interval(function () {

                //      		$scope.$apply(function(){
                var date = new Date();
                //获取图表的x轴
                var datax1 = [];
                for (var i = 0; i <= 144; i++) {
                    datax1.push(addMinutes(date, i * (-10)));
                }
                datax1[0] = '(今天)' + datax1[0];
                datax1[datax.length - 1] = datax1[datax1.length - 1] + '(昨天)';

                var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
                var month = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
                var nowDate = date.getDate(); //获取当前日(1-31)
                var hour = date.getHours(); //获取当前小时数
                var minutes = date.getMinutes(); //获取当前分钟数(0-59)
                var nowtime = year + '/' + month + '/' + nowDate + ' ' + hour + ':' + minutes + ':00'; //獲取當前時間整分鐘
                var endTime = new Date(nowtime).getTime(); //当前分钟的时间戳 单位：毫秒
                var startTime = endTime - 86400000; //24小时前的时间戳
                var startDate = timeChangetype(startTime); //把时间转换为为时间戳
                var endDate = timeChangetype(endTime);


                var searchData = {
                    'startDate': startDate / 1000, //時間戳單位為秒 开始时间秒数以00结尾
                    'endDate': endDate / 1000, //结束时间以秒数59结尾
                    'interval': 600 //單位為秒
                }

                var cachelenData = [];
                var priData = [];
                that.PostAjax(url, searchData, function (data) {
                    var findQueueData = data;
                    var cachelen = findQueueData.cachelen; //表示缓存队列
                    var pri = findQueueData.pri; //表示优先级队列
                    angular.forEach(cachelen, function (item) {
                        cachelenData.push(item.value);
                    })

                    angular.forEach(pri, function (item) {
                        priData.push(item.value);
                    })
                    option2.xAxis.data = datax1;
                    option2.series[0].data = cachelenData;
                    option2.series[1].data = priData;
                    myChart.setOption(option2, true);
                })
            }, 60000);


        },
        //一条线
        realTimeFn1: function (url, datax, id, title, lineName, Ytitle, color, data, $scope) {

            var that = this;
            var myChart = echarts.init(document.getElementById(id));
            // 指定图表的配置项和数据
            option1 = {
                title: {
                    text: title,
                    textStyle: {
                        color: '#ccc',
                        fontSize: 14,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: [lineName],
                    top: 25,
                    left: 150,
                    textStyle: { //图例文字的样式
                        color: '#2ec7c9',
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    show: true,
                    x: '80%',
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    name: '时间',
                    axisLine: {
                        lineStyle: {
                            color: '#ccc'
                        },
                    },
                    axisLabel: {
                        interval: 11 //8
                        //             	    rotate:30
                    },
                    nameLocation: 'end',
                    nameGap: 0,
                    type: 'category',
                    boundaryGap: false,
                    data: datax
                },
                yAxis: {
                    axisLine: {
                        lineStyle: {
                            color: '#ccc'
                        },
                    },
                    splitLine: {
                        show: false
                    },
                    name: Ytitle,
                    type: 'value'
                },
                color: ['#fff'],
                series: [{
                    name: lineName,
                    color: '#fff',
                    type: 'line',
                    //                   areaStyle: {
                    //                       normal: {
                    //                           color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    //                               offset: 0,
                    //                               color: color[0]
                    //                           }, {
                    //                               offset: 1,
                    //                               color: color[1]
                    //                           }]),
                    //                       }
                    //                   },
                    //                   lineStyle:{
                    //                       normal:{
                    //                         width:0.5,
                    //                         color:'#00FF00'
                    //                       }
                    //                   },
                    itemStyle: {
                        normal: {
                            color: "#ff0000",
                            lineStyle: {
                                color: "#ff0000"
                            },

                        }
                    },
                    showSymbol: false,
                    hoverAnimation: false,
                    data: data
                },

                    // {
                    //   name:'三级异常',
                    //   lineStyle:{
                    //         normal:{
                    //           width:0.5,
                    //           color:'#ff0000'
                    //         }
                    //     },
                    //   data:thirdData
                    // },
                    // {
                    //   name:'二级异常',
                    //   lineStyle:{
                    //         normal:{
                    //           width:0.5,
                    //           color:'#ff6000'
                    //         }
                    //     },
                    //   data:secondData
                    // },
                    // {
                    //   name:'一级告警',
                    //   lineStyle:{
                    //         normal:{
                    //           width:0.5,
                    //           color:'#ffc600'
                    //         }
                    //     },
                    //   data:fisrtData
                    // }
                ]
            };
            //获取当前时间n分钟后的时间函数
            function addMinutes(date, minutes) {
                minutes = parseInt(minutes);
                var interTimes = minutes * 60 * 1000;
                interTimes = parseInt(interTimes);
                var dateTime = new Date(Date.parse(date) + interTimes);
                var hour = dateTime.getHours();
                var min = dateTime.getMinutes();
                if (min < 10) {
                    min = '0' + min
                }
                return hour + ":" + min;
            }
            //时间格式转化为时间戳  
            function timeChangetype(stringTime) {
                var timestamp2 = Date.parse(new Date(stringTime));
                return timestamp2;
            }
            $scope.timer1 = $interval(function () {

                var date = new Date();
                //获取图表的x轴
                var datax1 = [];
                for (var i = 0; i <= 144; i++) {
                    datax1.push(addMinutes(date, i * (-10)));
                }
                datax1[0] = '(今天)' + datax1[0];
                datax1[datax.length - 1] = datax1[datax1.length - 1] + '(昨天)';

                var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
                var month = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
                var nowDate = date.getDate(); //获取当前日(1-31)
                var hour = date.getHours(); //获取当前小时数
                var minutes = date.getMinutes(); //获取当前分钟数(0-59)
                var nowtime = year + '/' + month + '/' + nowDate + ' ' + hour + ':' + minutes + ':00'; //獲取當前時間整分鐘
                var endTime = new Date(nowtime).getTime(); //当前分钟的时间戳 单位：毫秒
                var startTime = endTime - 86400000; //24小时前的时间戳
                var startDate = timeChangetype(startTime); //把时间转换为为时间戳
                var endDate = timeChangetype(endTime);


                var searchData = {
                    'startDate': startDate / 1000, //時間戳單位為秒 开始时间秒数以00结尾
                    'endDate': endDate / 1000, //结束时间以秒数59结尾
                    'interval': 600 //單位為秒
                }

                var findCurData = [];
                that.PostAjax(url, searchData, function (data) {
                    var findCur = data;
                    angular.forEach(findCur, function (item) {
                        findCurData.push(item.value);
                    })
                    option1.xAxis.data = datax1;
                    option1.series[0].data = findCurData;

                    myChart.setOption(option1, true);
                });
            }, 60000);
            myChart.setOption(option1);
        },

        /***
         **
         **统一监控饼图
         **
         */
        unifycircle: function (id, title, color, data) {
            var myChart = echarts.init(document.getElementById(id));
            option = {
                title: {
                    text: title,
                    x: 'left',
                    textStyle: {
                        color: '#ccc',
                        fontSize: 14,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                // legend: {
                //     orient: 'vertical',
                //     left: 'left',
                //     data: ['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
                // },
                color: color,
                calculable: true,
                series: [{
                    name: title,
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '50%'],
                    data: data,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            myChart.setOption(option);
        },
        /***
         **
         **统一监仪表图
         **
         */
        meterChart: function (url, id, title, valueint, max, $scope, time, str, units) {
            var myChart = echarts.init(document.getElementById(id));
            var max = max;
            var that = this;
            var chartData;
            option3 = {
                tooltip: {
                    //                formatter: "{c}%"  /*{a} <br/>{b} :*/
                    formatter: function (params) {
                        var str = (params['value'] / max * 100).toFixed(2) + '%';
                        return str;
                    }
                },
                toolbox: {
                    show: true,
                    x: '60%',
                    feature: {
                        //                    restore: {},
                        saveAsImage: {}
                    }

                },
                series: [{
                    //                    name:  '99',
                    type: 'gauge',
                    max: max,
                    detail: {
                        formatter: title + '\n' + '{value}' + units + '/分',
                        textStyle: {
                            fontSize: 12
                        },
                        offsetCenter: [0, '52%']
                    },
                    data: [{
                        value: valueint,

                    }],
                    axisLine: { // 坐标轴线
                        lineStyle: { // 属性lineStyle控制线条样式
                            color: [
                                [0.25, '#7ecc21'],
                                [0.5, '#ffc600'],
                                [0.75, '#ff6000'],
                                [1, '#ff0000']
                            ],
                            width: 10
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        show: false
                    },
                    splitLine: {
                        show: false
                    },
                    pointer: { // 分隔线  
                        color: '#EB7D64',
                        width: 5,
                        length: 52
                    }
                }]
            };

            $scope[time] = $interval(function () {

                titleName = title;
                that.PostAjax(url, {
                    'gateLinkIds': str
                }, function (data) {
                    angular.forEach(data, function (item) {
                        //此处遍历返回来的数据，根据id找到相应仪表图的数据value 来赋值  达到每分钟刷新一次
                        if (item.itemName == id) {
                            var unit;
                            if (item.unit == 1) {
                                unit = '万条';
                            } else {
                                unit = '条';
                            }
                            option3.series[0].data[0].value = item.valueInt;
                            option3.series[0].detail.formatter = title + '\n' + '{value}' + unit + '/分'
                            myChart.setOption(option3, true);
                        }
                    })
                })
            }, 60000);


            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option3);
        },
        /***
         **id 节点id不需要#
         **title  图表的标题
         **data   图表数据
         **time   图表时间
         **lineColor折线颜色
         **tomcat模态框折线图
         **
         */
        responseTime: function (id, title, data, time, lineColor) {
            var myChart = echarts.init(document.getElementById(id));
            option = {
                title: {
                    text: title,
                    show: false
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: [title]
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    axisLine: {
                        show: false
                    },
                    data: time,
                    axisTick: {
                        show: false
                    }
                },

                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    }
                },
                series: [{
                    name: title,
                    type: 'line',
                    lineStyle: {
                        normal: {
                            color: lineColor
                        }
                    },
                    stack: '',
                    data: data,
                    markLine: {
                        symbol: 'circle',
                        symbolSize: 1,
                        label: {
                            normal: {
                                position: 'middle',
                                formatter: function () {
                                    return '阀值上限200'
                                }
                            }
                        },
                        lineStyle: {
                            normal: {
                                type: 'solid',
                                color: 'red'
                            }
                        },
                        data: [{
                            name: '平均线',
                            type: 'average',
                            yAxis: 200
                        }

                        ]
                    },
                }]
            };
            myChart.setOption(option);
        },
        /***
         **index  序号
         **event  事件
         **num    第几个选项
         **多选框取值函数,前提数组命名一致
         **
         */
        //添加和删除预警接收人
        addAndDelRecevier: function (obj) {

            obj.addRecevier = function () {
                if (obj.ifAdd) {
                    if (obj.alarmusers.length == 0) {
                        App.alert('没有可添加的预警接收人');
                        return
                    }

                    obj.addData.alarmRecUser.push({
                        'rceId': obj.alarmusers[0].rceId,
                        'phone': obj.alarmusers[0].phone,
                        'email': obj.alarmusers[0].email,
                        'userType': obj.alarmusers[0].userType,
                        'recAlarmLevel1': bool(obj.alarmusers[0].recAlarmLevel1),
                        'recAlarmLevel2': bool(obj.alarmusers[0].recAlarmLevel2),
                        'recAlarmLevel3': bool(obj.alarmusers[0].recAlarmLevel3),
                    })
                } else {
                    App.alert('该主机没有指标名称可添加')
                }
            };
            obj.delRecevier = function (index) {
                obj.addData.alarmRecUser.splice(index, 1)
            }

            function bool(data) {
                if (data == '1') {
                    return true
                } else {
                    return false
                }
            }

        },
        /***
         **url 保存路径
         **主机总监控保存
         **obj $scope对象
         */

        alarmPerson: function (url, obj) {


            if (obj.addData.alarmRecUser.length <= 0) {
                App.alert('请添加预警接收人');
                return
            }

            //判断重名不给保存
            var keyFlag = false;
            var personFlag = false;
            for (var i = 0; i < obj.addData.alarmRecUser.length; i++) {
                for (var j = i + 1; j < obj.addData.alarmRecUser.length; j++) {
                    if (obj.addData.alarmRecUser[i].rceId == obj.addData.alarmRecUser[j].rceId) {
                        personFlag = true;
                    }
                }
            }
            for (var i = 0; i < obj.addData.index.length; i++) {
                for (var j = i + 1; j < obj.addData.index.length; j++) {
                    if (obj.addData.index[i].keyId == obj.addData.index[j].keyId) {
                        keyFlag = true;
                    }
                }
            }
            if (keyFlag) {
                App.alert('监控指标重名无法添加');
                return
            }
            if (personFlag) {
                App.alert('预警接收人重名无法添加');
                return
            }

            var sendData = angular.copy(obj.addData);
            for (var i = 0; i < sendData.alarmRecUser.length; i++) {
                if (sendData.alarmRecUser[i].recAlarmLevel1) {
                    sendData.alarmRecUser[i].recAlarmLevel1 = '1';
                } else {
                    sendData.alarmRecUser[i].recAlarmLevel1 = '0';
                }
                if (sendData.alarmRecUser[i].recAlarmLevel2) {
                    sendData.alarmRecUser[i].recAlarmLevel2 = '1';
                } else {
                    sendData.alarmRecUser[i].recAlarmLevel2 = '0';
                }
                if (sendData.alarmRecUser[i].recAlarmLevel3) {
                    sendData.alarmRecUser[i].recAlarmLevel3 = '1';
                } else {
                    sendData.alarmRecUser[i].recAlarmLevel3 = '0';
                }
            }


            sendData.index = encodeURI(JSON.stringify(sendData.index));
            sendData.alarmRecUser = encodeURI(JSON.stringify(sendData.alarmRecUser));

            this.PostAjax(url, sendData, function (data) {
                if (data.status == 0) {
                    App.alert('保存成功', function () {
                        $('#add1').modal('hide');
                    })
                } else {
                    App.alert(data.msg);
                }
            })
        },

        /***
         **eleName 一整个时间插件的节点名称，可以是id也可以是.
         **fomate  时间的格式开始的时间视图 
         **startView  4为年视图，往上问月，日，时，分秒
         **minView  显示的最小视图
         */

        DateTimePicker: function (obj, eleName, formate, startView, minView, timeStatus) {
            //时间调用
            $.fn.datetimepicker.dates['zh'] = {
                days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
                daysShort: ["日", "一", "二", "三", "四", "五", "六", "日"],
                daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
                months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                monthsShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
                meridiem: ["上午", "下午"],
                //suffix:      ["st", "nd", "rd", "th"],  
                today: "今天"
            };
            $(eleName).datetimepicker({
                language: 'zh',
                format: formate,
                autoclose: 1,
                weekStart: 1,
                startDate: DateFormate(new Date("2015.12.12")),
                todayBtn: 'linked',
                todayHighlight: 1,
                startView: startView,
                minView: minView
            }).on('hide', function (ev) {
                var str = DateFormate(ev.date)
                obj.$apply(obj.searchData[timeStatus] = str);


            });
            function DateFormate(date) {
                var str = '';
                switch (formate) {
                    case 'yyyy':
                        str = date.getFullYear()
                        break;
                    case 'yyyy-mm':
                        str = date.getFullYear() + '-' + (date.getMonth() + 1);
                        break;
                    case 'yyyy-mm-dd':
                        str = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + 1);
                        break;
                }
                return str
            }

        },

        /***
         ****改变预警接收人
         *****index  传入数据的序号
         *****obj    $scope
         */

        changeRecUser: function (obj) {
            var that = this;
            obj.changeRecUser = function (index) {
                for (var i = 0; i < obj.alarmusers.length; i++) {
                    if (obj.alarmusers[i].rceId == obj.addData.alarmRecUser[index].rceId) {
                        obj.addData.alarmRecUser[index] = {
                            'rceId': obj.alarmusers[i].rceId,
                            'phone': obj.alarmusers[i].phone,
                            'email': obj.alarmusers[i].email,
                            'userType': obj.alarmusers[i].userType,
                            'recAlarmLevel1': that.bool(obj.alarmusers[i].recAlarmLevel1),
                            'recAlarmLevel2': that.bool(obj.alarmusers[i].recAlarmLevel2),
                            'recAlarmLevel3': that.bool(obj.alarmusers[i].recAlarmLevel3),
                        }
                    }
                }

            }

        },



        //将0,1数字转换成布尔值
        bool: function (data) {
            if (data == '1') {
                return true
            } else {
                return false
            }
        },


        /***
         ****业务端下拉级联
         *****obj  $scope
         *****
         */
        setSms: function (obj) {
            var that = this
            that.PostAjax('/svrNodeDef/getSvrNode', {}, function (data) {
                obj.listData1 = data;
                //短信级联
                obj.getSms = function () {

                    obj.searchData.serviceCode = "";
                    that.PostAjax('/serviceCodeDef/getBySvrNode', {
                        "svrNode": obj.searchData.svrNode
                    }, function (data) {
                        obj.listData2 = data;
                    })
                },
                    obj.getSms1 = function () {

                        obj.searchData.serviceCode = "";
                        that.PostAjax('/serviceCodeDef/getBySvrNode', {
                            "svrNode": obj.searchData1.svrNode
                        }, function (data) {
                            obj.listData2 = data;
                        })
                    }
            })

        },
        //下拉ajax
        getServiceCode: function (obj, key, svrNode) {
            this.PostAjax('/serviceCodeDef/getBySvrNode', {
                "svrNode": svrNode
            }, function (data) {
                obj[key] = data;
            })
        },
        //修改和添加，下拉级联
        changeSvrNode: function (obj) {
            var that = this;
            obj.getServiceCode = function () {
                obj.addData.serviceCode = '';
                if (obj.addData.svrNode == '') {
                    obj.addData.serviceCode = ''
                }
                that.PostAjax('/serviceCodeDef/getBySvrNode', {
                    "svrNode": obj.addData.svrNode
                }, function (data) {
                    obj.serviceList = data;
                })
            }
        },

        /***
         ****oracle监控,redis监控,tomcat监控
         *****
         *****
         */
        //选择ip后更新数据
        hostSelectIp: function (obj, data) {
            var that = this;

            obj.addData.indexnames = data.data.indexnames;
            obj.addData.alarmusers = data.data.alarmusers;

            //将0,1转成布尔值
            for (var i = 0; i < data.data.alarmusers.length; i++) {
                obj.addData.alarmusers[i].recAlarmLevel1 = that.bool(data.data.alarmusers[i].recAlarmLevel1);
                obj.addData.alarmusers[i].recAlarmLevel2 = that.bool(data.data.alarmusers[i].recAlarmLevel2);
                obj.addData.alarmusers[i].recAlarmLevel3 = that.bool(data.data.alarmusers[i].recAlarmLevel3);
            }

            //给下拉框值
            obj.alarmusers = angular.copy(data.data.alarmusers);
            obj.indexnames = angular.copy(data.data.indexnames);

        },
        //删除添加指标，删除添加监控人
        hostDelandAdd: function (obj) {
            var that = this;
            //添加和删除预警接收人
            obj.ifAdd = true;
            obj.addRecevier = function () {
                if (obj.ifAdd) {
                    if (obj.alarmusers.length == 0) {
                        App.alert('没有可添加的预警接收人');
                        return
                    }
                    obj.addData.alarmusers.push({
                        'rceId': obj.alarmusers[0].rceId,
                        'phone': obj.alarmusers[0].phone,
                        'email': obj.alarmusers[0].email,
                        'userType': obj.alarmusers[0].userType,
                        'recAlarmLevel1': that.bool(obj.alarmusers[0].recAlarmLevel1),
                        'recAlarmLevel2': that.bool(obj.alarmusers[0].recAlarmLevel2),
                        'recAlarmLevel3': that.bool(obj.alarmusers[0].recAlarmLevel3),
                    })


                } else {
                    App.alert('该主机没有指标名称可添加')
                }
            };
            obj.delRecevier = function (index) {
                obj.addData.alarmusers.splice(index, 1)
            }


            //添加和删除监控指标名称
            obj.addIndex = function () {
                if (obj.indexnames.length == 0) {
                    App.alert('没有可添加的监控指标');
                    return
                };
                obj.addData.indexnames.push({
                    'keyId': obj.indexnames[0].keyId,
                    'upperLimit': '',
                    'lowerLimit': '',
                    'remark': ''
                })
            }
            obj.delIndex = function (index) {
                obj.addData.indexnames.splice(index, 1)
            }

        },
        //保存监控配置
        hostSaveMonitor: function (url, obj) {
            var that = this
            //接收预警信息
            var personFlag = false;
            var keyFlag = false;
            if (obj.addData.alarmusers.length == 0) {
                App.alert('请添加预警接收人')
            }
            for (var i = 0; i < obj.addData.alarmusers.length; i++) {
                for (var j = i + 1; j < obj.addData.alarmusers.length; j++) {
                    if (obj.addData.alarmusers[i].rceId == obj.addData.alarmusers[j].rceId) {
                        personFlag = true;
                    }
                }
            }
            for (var i = 0; i < obj.addData.indexnames.length; i++) {
                for (var j = i + 1; j < obj.addData.indexnames.length; j++) {
                    if (obj.addData.indexnames[i].keyId == obj.addData.indexnames[j].keyId) {
                        keyFlag = true;
                    }
                }
            }
            if (keyFlag) {
                App.alert('监控指标不能重名');
                return
            }
            if (personFlag) {
                App.alert('预警接收人不能重名');
                return
            }


            var sendData = angular.copy(obj.addData);
            //将预警等级换成0或1
            for (var i = 0; i < sendData.alarmusers.length; i++) {
                if (sendData.alarmusers[i].recAlarmLevel1) {
                    sendData.alarmusers[i].recAlarmLevel1 = '1';
                } else {
                    sendData.alarmusers[i].recAlarmLevel1 = '0';
                }
                if (sendData.alarmusers[i].recAlarmLevel2) {
                    sendData.alarmusers[i].recAlarmLevel2 = '1';
                } else {
                    sendData.alarmusers[i].recAlarmLevel2 = '0';
                }
                if (sendData.alarmusers[i].recAlarmLevel3) {
                    sendData.alarmusers[i].recAlarmLevel3 = '1';
                } else {
                    sendData.alarmusers[i].recAlarmLevel3 = '0';
                }
            }

            sendData.indexnames = encodeURI(JSON.stringify(sendData.indexnames));
            sendData.alarmusers = encodeURI(JSON.stringify(sendData.alarmusers));

            that.PostAjax(url, sendData, function (data) {
                if (data.status == 0) {
                    App.alert('保存成功', function () {
                        $('#add1').modal('hide');
                    })
                } else {
                    App.alert(data.msg);
                }
            })


        },

    };
    return factory;
})

app.directive('onFinishRenderFilters', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit('ngRepeatFinished');
                });
            }
        }
    };
});